#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado
import tornado.web
import datetime
import os
import re
import json
from config import etc
from controls import data_user_brief_mysql
from controls import data_user_buddy_mysql
from controls import data_topic_note_mysql
from controls import data_topic_note_img_mysql
from controls import data_img_base_mysql
from controls import data_topic_note_like_mysql
from controls import data_topic_title_mysql
from utils import log
from utils.session_base import ApiHost, ApiGuest
from utils.session_mc import BaseHandler


class GetBuddyFeedHandler(BaseHandler):
    @ApiGuest
    def post(self, *args, **kwargs):
        userid = self.ss_params.get('userid', None)
        begin = self.ss_params.get('begin', None)
        limit = self.ss_params.get('limit', None)

        if userid and begin and limit is None:
            log.w('params fetching error')
            res = {'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        userid_list = data_user_buddy_mysql.get_user_follow_by_userid_only(userid)
        if userid_list is None:
            log.w('follow userid is none')
            res = {'idx':self.ss_idx, 'ret':0, 'msg':'no follow user', 'res':{}}
            self.write(json.dumps(res))
            self.finish()
            return
        note_list = data_topic_note_mysql.get_topic_note_by_userid_list(userid_list, begin, limit)
        noteid_list = [item['noteid'] for item in note_list]
        topicid_list = {}.fromkeys([item['topicid'] for item in note_list]).keys()
        log.i('[topicid_list] %s' % topicid_list)
        topic_dict = data_topic_title_mysql.get_topic_title_dict_by_topicid_list(topicid_list)
        log.i('[topic_dict] %s' % topic_dict)
        note_img_list = data_topic_note_img_mysql.get_topic_note_img_by_noteid_list(noteid_list)

        all_imgid_list = []
        note_img_list_map = {}
        for item in note_img_list:
            all_imgid_list += item['imgid']
            note_img_list_map[item['noteid']] = item['imgid']
        note_img_map = data_img_base_mysql.get_img_url_by_imgid_list(all_imgid_list)
        user_brief_map = data_user_brief_mysql\
            .get_user_brief_map_by_userid_list(userid_list)
        note_like_count_map = data_topic_note_like_mysql\
            .get_note_like_count_map_by_noteid_list(noteid_list)

        for item1 in note_list:
            noteid = item1['noteid']
            userid = item1['userid']
            topicid = item1['topicid']
            item1['user'] = user_brief_map[userid]
            item1['user']['thumblink'] = item1['user']['imglink'][0:len(item1['user']['imglink'])-1] + '132'
            item1['like_count'] = note_like_count_map.get(noteid, 0)
            item1['imgs'] = []
            item1['thumbs'] = []
            item1['topic'] = topic_dict[topicid]['title']
            temp_img_list = note_img_list_map.get(noteid, [])
            for item2 in temp_img_list:
                if item2 in note_img_map.keys():
                    item1['imgs'].append(note_img_map[item2])
                    item1['thumbs'].append(re.sub("(.*)(\.[a-z0-9]{1,4})$", r"\1_100\2", note_img_map[item2]))
        if self.current_user:
            current_userid = self.current_user.get('userid', None)
            current_user_like_list = data_topic_note_like_mysql\
                .get_note_like_by_noteid_list_and_userid(noteid_list, current_userid)
            for item in note_list:
                if item['noteid'] in current_user_like_list:
                    item['liked'] = 1
                else:
                    item['liked'] = 0

            res = {'idx': self.ss_idx, 'ret': 0, 'msg': '获取成功', 'res': note_list}
            self.write(json.dumps(res))
            self.finish()
            return
        else:
            res = {'idx': self.ss_idx, 'ret': 0, 'msg': '获取成功', 'res': note_list}
            self.write(json.dumps(res))
            self.finish()
            return

class ApiNotFindHandler(BaseHandler):
    def get(self):
        raise tornado.web.HTTPError(503)
    @tornado.web.asynchronous
    def post(self):
        log.i(self)
        res = {'idx':0, 'ret':9, 'msg':'无此功能', 'res':{}}
        self.write(json.dumps(res))
        self.finish()